<template>
   <div class="'applyFor'">
      <van-form @submit="onSubmit" :disabled=flag readonl="true">
         <van-field style="color:gray;" v-model="specialistInfo.name" required label="姓名" name="name"
            placeholder="请输入姓名" :rules="[{ required: true, message: '请输入姓名' }]" />

         <van-field required v-model="specialistInfo.identity" name="identity" label="身份证号" placeholder="请输入身份证号"
            :rules="[{ required: true, message: '请填写身份证号' }]" />

         <van-field required v-model="specialistInfo.citystr" name="city" is-link readonly label="地区" placeholder="请选择所在地区"
            @click="selectLocal" :rules="[{ required: true, message: '请选择所在地区' }]" />
         <van-popup v-model="show" round position="bottom">
            <van-cascader v-model="cascaderValue" title="请选择所在地区" :options="options"
               @close="show = false" @finish="onFinish" :field-names="fieldNames" />
         </van-popup>

         <van-field v-model="specialistInfo.company" label="所在单位" name="company" placeholder="请输入所在单位" />

         <van-field v-model="specialistInfo.level" label="职称" name="level" placeholder="请输入职称" />

         <van-field readonly clickable name="type" :value="specialistInfo.type" label="专家类型" placeholder="请选择专家类型"
            @click="selectSpecialist" icon="shop-o" />
         <van-popup v-model="showPicker" position="bottom">
            <van-picker show-toolbar :columns="columns" @confirm="onConfirm" @cancel="showPicker = false" />
         </van-popup>

         <van-field v-model="specialistInfo.expertise" label="擅长领域" name="expertise" placeholder="请输入擅长领域" />

         <van-field name="uploader" label="资格证书">
            <template #input>
               <van-uploader :after-read="upload" :disabled=flag multiple max-count="10"
                  v-model="certificateList" />
            </template>
         </van-field>
         <div style="margin: 16px;">
            <van-button round block type="info" native-type="submit">提交</van-button>
         </div>
      </van-form>
   </div>
</template>
<script>
import { Toast } from 'vant';
import store from '@/store'
import API from '../../services/index'
import axios from 'axios'
export default {
   data() {
      return {
         flag: false,
         num: 0,
          cascaderValue: '',//选择市区的value值
         specialistInfo: {
            name: '',//姓名
            identity: '',//密码
            company: '',//单位
            level: '',//职称
            expertise: "",//擅长领域
            type: '',//专家类型
            city: '',//所选地区
            certificate: '',
         },
         certificateList:[],
         columns: ['农资专家', '农机专家', '肥料专家'], //专家类型数组
         show: false,//控制所选地区的弹框
         show1: false,//控制专家类型的弹框
         showPicker: false,
         fieldNames: {  //自定义字段名称
            text: 'name',
            value: 'id',
            //children: 'children',
         },
         // 选项列表，children 代表子选项，支持多级嵌套
         options: [],
      };
   },
   watch: {

   },
   created() {

   },
    mounted() {
      if (this.$route.params.flag&&this.$route.params.action=='edit') {
         this.getExpert();
      } else {
         this.getAddress()
         this.specialistInfo = {certificateList:[]}
      }
      
   },
   methods: {
      //获取专家提交的信息
      async getExpert(){
         const resoptions = await API.getArea({
            params: { pid:45,type:1}
         })
         resoptions.forEach((v, i) => {
            delete v["children"]
         })
         this.options = resoptions
         

         const res = await API.getExpert({})
         let certificateList=[];
         if(res.certificate){
            let urlList=res.certificate.split(',');
            urlList.forEach(item=>{
               certificateList.push({url:item})
            })
         }
         //专家类型
         let type="";
         if(res.type==0)type='农资专家';
         if(res.type==1)type='农机专家';
         if(res.type==2)type='肥料专家';

         //地区
         let citystr=resoptions.find(ele=>{
            return ele.id==res.city
         })

         this.specialistInfo=res;
         this.certificateList=certificateList;
         this.specialistInfo.certificateList=certificateList;
         this.specialistInfo.type=type;
         this.specialistInfo.citystr=citystr.name;
      },
      //提交
      async onSubmit(values) {
          if (values.type == "农资专家") {
            values.type = 0
         } else if (values.type == "农机专家") {
            values.type = 1
         } else {
            values.type = 2
         }
         values.city=this.specialistInfo.city;
         if(this.specialistInfo.id){
            values.expertId=this.specialistInfo.id;
            let certificateList=this.specialistInfo.certificateList.map(ele=>{return ele.url})
            values.certificate=certificateList.join(',');
            console.log(values)
            const res = await API.updateExpert({
               data: values
            })
            let info = JSON.stringify(values)
            localStorage.setItem("info", info)
            this.$router.replace({name:"submitSuccess",params:{submitState:0}})
         
         }else{
            const res = await API.saveExpert({
               data: values
            })
            let info = JSON.stringify(values)
            localStorage.setItem("info", info)
            // this.$router.push("/submitSuccess")
            this.$router.replace({name:"submitSuccess",params:{submitState:0}})
         }
         
      },
      //获取地区
      async getAddress() {
         const res = await API.getArea({
            params: { pid:45,type:1}
         })
         res.forEach((v, i) => {
            delete v["children"]
         })
         this.options = res
      },
      //选择地区的事件
      onFinish({ selectedOptions }) {
         this.show = false;
         this.specialistInfo.city = selectedOptions.map((option) => option.id).join('/');
         this.specialistInfo.citystr = selectedOptions.map((option) => option.name).join('/');
      },
      //控制专家类型的事件
      onSelect(item) {
         // 默认情况下点击选项时不会自动收起
         // 可以通过 close-on-click-action 属性开启自动收起
         this.show1 = false;
         Toast(item.name);
      },
      //选择专家类型确认
      onConfirm(value) {
         console.log(value)
         this.specialistInfo.type = value;
         this.showPicker = false;
      },
      selectLocal() {
         //用来判断选择框是否被禁用
         if (this.$route.params.flag) {
            this.show = true
         } else (
            this.show = false
         )
      },
      selectSpecialist() {
         //用来判断选择框是否被禁用
         if (this.$route.params.flag ) {
            this.showPicker = true
         } else (
            this.showPicker = false
         )
      },
      //图片上传
      async upload(file) {
         var formdata = new FormData()
         if(file instanceof Array && file.length){
           for (let i = 0; i < file.length; i++) {
               formdata.append("file", file[i].file);
           }
         }else{
           formdata.append("file", file.file);
         }

          formdata.append("type",'1')
         const res = await API.uploadimg({
            data: formdata
         })
         this.specialistInfo.certificateList.push({url:res.url});
      },

   },
};
</script>
<style scoped>
::v-deep .van-uploader__preview {
   position: relative;
   margin: 0 8px 8px 0;
   cursor: pointer;
   /* width: 65% !important; */
}
::v-deep .van-uploader__preview-image {
   width: 80px !important;
   height: 80px !important;
}
</style>